<?php

namespace app\api\controller\xmwechat;

use app\common\controller\Frontend;
use app\common\library\xmwechat\offiaccount\MessageService;
use app\common\library\xmwechat\offiaccount\OaService;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\Request;

/**
 * 公众号
 */
class Offiaccount extends Frontend
{

    // 测试结束请删除下方数组里的 sendTemplateMessage
    protected array $noNeedLogin = ['messageServe', 'oauth', 'sendTemplateMessage'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 公众号服务器推送
     * @param Request $request
     * @author jsjxsz <QQ:1365962177>
     */
    public function messageServe(Request $request)
    {
        try {
            $params = $request->param(['signature', 'timestamp', 'nonce', 'echostr']);
            if (isset($params['echostr']) && !empty($params['echostr'])) {
                $res = MessageService::getInstance()->checkSignature($params);
                if ($res !== false) {
                    echo $params['echostr'];
                } else {
                    echo '验证失败';
                }
                exit();
            }
            return MessageService::getInstance()->messageServe();
        } catch (ValidateException|PDOException $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 微信公众号网页授权示例
     * @throws \Exception
     * @author jsjxsz <QQ:1365962177>
     */
    public function oauth(Request $request)
    {
        $code = $request->param('code');
        if (!isset($code)) {
            try {
                $redirectUrl = OaService::getInstance()->getRedirectUrl();
                header("Location: {$redirectUrl}");
                exit();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
        }

        $result = OaService::getInstance()->oauthCallback($code);
        // header("Content-ProjectType: application/json");
        if (!isset($result['openid'])) {
            $this->error('获取openid失败');
            throw new \Exception('获取openid失败');
        }
        // 获取openid后，写你自己的逻辑

        $this->success('success');
    }

    /**
     * 发送模板消息示例
     * @param Request $request
     * @return void
     * @throws \Exception
     * @author jsjxsz <QQ:1365962177>
     */
    public function sendTemplateMessage(Request $request): void
    {
        $openid      = 'oluKa548P2NdCeiEbvlAomQxLKfM';
        $template_id = 'A2XBZz1bhyHG9Uccol0MEQ3jKgHYAIv9it5wWvG8Nng';
        $data        = [
            'thing3'            => ['value' => '这里是消费门店', 'color' => '#888888'],
            'thing5'            => ['value' => '这里是服务名称', 'color' => '#888888'],
            'amount2'           => ['value' => '100.99元', 'color' => '#888888'],
            'time11'            => ['value' => date('Y-m-d H:i'), 'color' => '#888888'],
            'character_string1' => ['value' => time() . rand(999999, 1000000), 'color' => '#888888'],
        ];
        // 模板跳转链接,不跳转可忽略此参数
        $url = '';
        // 跳小程序所需数据,不需跳小程序可不用传该数据，小程序appid必须已绑定关联当前公众号
        $miniprogram = [
            'appid'    => '',
            'pagepath' => ''
        ];

        $result = OaService::getInstance()->sendTemplateMessage($openid, $template_id, $data, $url, $miniprogram);
        if ($result !== false) {
            $this->success('发送成功');
        } else {
            $this->error('发送失败');
        }

    }

}